package com.jiegui.modules.common.interceptor;



import com.jiegui.common.core.redis.RedisCache;
import com.jiegui.common.exception.user.RRException;
import com.jiegui.modules.common.annotation.Login;
import com.jiegui.modules.utils.JwtUtils;
import com.jiegui.wx.domain.WechatUser;
import com.jiegui.wx.service.IWechatUserService;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限(Token)验证
 *
 *
 * @date 2020-06-19 15:38
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private JwtUtils jwtUtils;

    public static final String USER_ID_KEY = "userId";

    public static final String USER_KEY = "user";

    @Autowired
    private RedisCache redisCache;

    @Resource
    IWechatUserService wechatUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }
        if(annotation != null){
            return true;
        }
        //获取用户凭证
        String token = request.getHeader(jwtUtils.getHeader());
        if(StringUtils.isBlank(token)){
            token = request.getParameter(jwtUtils.getHeader());
        }
        String validStr = redisCache.getCacheObject(token);
        //凭证为空
        if(StringUtils.isBlank(token) || StringUtils.isBlank(validStr)){
            throw new RuntimeException("请先登录");
        }

        Claims claims = jwtUtils.getClaimByToken(token);
        if(claims == null || jwtUtils.isTokenExpired(claims.getExpiration())){
            RRException ex=  new RRException(jwtUtils.getHeader() + "失效，请重新登录",412);
            throw ex;
        }
        Long userId = Long.parseLong(claims.getSubject());
        WechatUser user = wechatUserService.getById(userId);
        if (null == user){
            throw new RRException("请先登录", HttpStatus.UNAUTHORIZED.value());
        }
        request.setAttribute(USER_KEY, user);
        request.setAttribute(USER_ID_KEY, userId);
        return true;
    }
}
